package com.example.order.controller;

import com.alibaba.nacos.common.utils.ThreadUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.core.domain.Result;
import com.example.order.entity.Order;
import com.example.order.service.OrderService;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RefreshScope
@RequestMapping("/order")
public class OrderController {

    public static AtomicInteger count =  new AtomicInteger(0);

    @Autowired
    private OrderService orderService;

    @GetMapping("/{id}")
    public Result<Order> getById(@PathVariable Long id) {
        return Result.success(orderService.getById(id));
    }

    @PostMapping
    public Result<Order> create(@RequestBody Order order) {
        return Result.success(orderService.createOrder(order.getUserId(), order.getProductId(), order.getQuantity()));
    }

    @PutMapping
    public Result<Boolean> update(@RequestBody Order order) {
        return Result.success(orderService.updateById(order));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        return Result.success(orderService.removeById(id));
    }

    @PostMapping("/{id}/pay")
    public Result<Boolean> pay(@PathVariable Long id) {
        return Result.success(orderService.payOrder(id));
    }

    @PostMapping("/{id}/cancel")
    public Result<Boolean> cancel(@PathVariable Long id) {
        return Result.success(orderService.cancelOrder(id));
    }

    @GetMapping
    public Result<Page<Order>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long userId) {
        
        Page<Order> page = new Page<>(current, size);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null, Order::getUserId, userId);
        wrapper.orderByDesc(Order::getCreateTime);
        
        return Result.success(orderService.page(page, wrapper));
    }

    @GetMapping("/create-fixed")
    public Result<Order> createFixedOrder() {
//         直接调用service层的createOrder方法
//         参数：用户ID=1，商品ID=1，数量=2
//        System.out.println("{}商品调用{}"+ DateUtils.formatDate(new Date()));
        return Result.success(orderService.createOrder(1L, 1L, 2));
//        System.out.println(count.addAndGet(1));
//        return null;
    }
}